﻿<template>
    <el-container>
        <el-header>
            <div class="left-panel">
                <!-- <el-button
                    type="primary"
                    icon="el-icon-plus"
                    :disabled="!addState"
                    @click="exportExcel"
                >导出</el-button>
                <el-button
                    type="primary"
                    icon="el-icon-plus"
                    :disabled="!addState"
                    @click="opBatchSend"
                >发货</el-button>-->
            </div>
            <div class="right-panel">
                <el-button :icon="Search"   type="primary" @click="opBindData">查询</el-button>
                <el-button :icon="Search" type="info" plain @click="resetSearch">重置</el-button>
                <el-button text type="primary" @click="showCondition = !showCondition">
                    <span v-if="!showCondition">展开</span>
                    <span v-else>收起</span>
                    <vab-icon
                        class="vab-dropdown"
                        :class="{ 'vab-dropdown-active': fold }"
                        icon="arrow-up-s-line"
                    />
                </el-button>
            </div>
        </el-header>
        <el-foot v-show="showCondition">
            <vab-query-form-top-panel>
                <el-form inline label-width="49px" :model="queryForm" style="margin-top: 5px">
                    <el-form-item label="要货单位" label-width="100px">
                        <sc-store-select
                            ref="orgselect"
                            :props="storeProps"
                            :selectKeyValue="'storeId'"
                            v-model="queryList.stores"
                            @fatherMethod="storeSelectProcess"
                        ></sc-store-select>
                    </el-form-item>
                    <el-form-item label="要货时间" label-width="100px">
                        <el-date-picker
                            style="width: 300px"
                            v-model="queryList.applyDates"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="defaultTime"
                        />
                    </el-form-item>
                    <el-form-item label="期望到货日期" label-width="100px">
                        <el-date-picker
                            style="width: 300px"
                            v-model="queryList.expectedDates"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="defaultTime"
                        />
                    </el-form-item>
                    <el-form-item label="要货申请编号" label-width="100px">
                        <el-input
                            placeholder="---请输入名称---"
                            v-model="queryList.applyOrderCode"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="采购/配送订单编号" label-width="100px">
                        <el-input
                            placeholder="---请输入名称---"
                            v-model="queryList.purchaseOrderCode"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="供应商" label-width="100px" v-if="orgType==1">
                        <sc-supplier-select
                            ref="orgselect"
                            :props="supplierProps"
                            :selectKeyValue="'supplierId'"
                            v-model="queryList.suppliers"
                            @fatherMethod="supplierSelectProcess"
                        ></sc-supplier-select>
                    </el-form-item>
                    <el-form-item label="物料编码" label-width="100px">
                        <el-input
                            placeholder="---请输入名称---"
                            v-model="queryList.materialCode"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="物料名称" label-width="100px">
                        <el-input
                            placeholder="---请输入名称---"
                            v-model="queryList.materialName"
                            style="width: 300px"
                        />
                    </el-form-item>
                    <el-form-item label="单据状态" label-width="100px">
                        <el-select
                            placeholder="---请选择状态---"
                            v-model="queryList.status"
                            style="width: 300px"
                        >
                            <el-option label="---请选择---" value />
                            <el-option
                                v-for="item in optionsState"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="下单时间" label-width="100px">
                        <el-date-picker
                            style="width: 300px"
                            v-model="queryList.crDates"
                            type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            range-separator="-"
                            unlink-panels="true"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :default-time="defaultTime"
                        />
                    </el-form-item>
                </el-form>
            </vab-query-form-top-panel>
        </el-foot>

        <el-main class="nopadding">
            <scTable
                ref="mytable"
                :queryType="'refund-purchase-order/pages'"
                :data="listData"
                :queryList="queryList"
                :column="columnList"
                :orderList="OrderList"
                :sort-orders="['ascending', 'descending']"
                @selection-change="selectionChange"
                row-key="purchaseOrderId"
                key="purchaseOrderId"
                :isKeyDown="showCondition" 
                :pageSize="10"
                :row-class-name="setRowClass"
                show-summary
                remoteSummary
            >
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column label="退回时间" prop="refundDate" width="120" sortable>
                    <template #default="scope">{{scope.row.refundDate?.slice(0,10)}}</template>
                </el-table-column>
                <el-table-column label="退回人" prop="refundName" width="120" sortable></el-table-column>
                <el-table-column label="供应商" prop="supplierName" width="120" sortable></el-table-column>
                <el-table-column label="退回/撤回物料" prop="materialDesc"  width="180">
                    <template #default="scope">
                        <el-popover placement="bottom-start" :width="500" trigger="click">
                            <template #reference>
                                <div
                                    style="position: relative;text-overflow: ellipsis;white-space: nowrap;cursor: pointer;display: block;"
                                >
                                    <span v-for="item in scope.row.refundPurchaseOrderItems" :key="item" style="color: #318cf3;">
                                        {{item.materialName}}/{{item.qty}}{{item.unitName}};
                                    </span>
                                </div>
                            </template>
                            <el-table :data="scope.row.refundPurchaseOrderItems" style="width: 100%" stripe>
                                <el-table-column prop="materialName" label="物料名称" min-width="140" />
                                <el-table-column prop="qty" label="数量" min-width="80" />
                                <el-table-column prop="unitName" label="单位" min-width="80" />
                            </el-table>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="要货单位" prop="storeName" width="180" sortable></el-table-column>
                <el-table-column label="单据金额" prop="refundAmount" width="180" sortable>
                    <template #default="scope">{{scope.row.refundAmount?.toFixed(2)}}</template>
                </el-table-column>
                <el-table-column label="采购订单类型" prop="purchaseTypeDesc" width="180" sortable></el-table-column>
                <el-table-column label="关联要货订单" prop="applyOrderCode" width="180" sortable>
                    <template #default="scope">
                        <span
                            class="el-span-text"
                            @click="opApplyShow(scope.row, scope.$index)"
                        >{{scope.row.applyOrderCode}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="采购/配送订单编号" prop="purchaseOrderCode" width="180" sortable>
                    <template #default="scope">
                        <span
                            class="el-span-text"
                            v-if="scope.row.orderType==1"
                            @click="opShow(scope.row, scope.$index)"
                        >{{scope.row.deliveryOrderCode}}</span>
                        <span
                            class="el-span-text"
                            @click="opShow(scope.row, scope.$index)"
                        >{{scope.row.purchaseOrderCode}}</span>
                    </template>
                </el-table-column>
                
              
              
              
                <el-table-column label="备注" prop="remarks" width="180" sortable></el-table-column>
                
               
                <el-table-column label="单据状态" prop="statusDesc" width="180" sortable></el-table-column>
                <el-table-column label="操作" fixed="right" align="right" width="240">
                    <template #default="scope">
                        <el-button-group>
                            <el-button
                                text
                                type="primary"
                                size="small"
                                @click="opShow(scope.row, scope.$index)"
                            >查看</el-button>
                            <el-button
                                text
                                type="primary"
                                size="small"
                                v-show="orgType==1&&scope.row.status!=4&&scope.row.status!=9"
                                @click="opReceive(scope.row, scope.$index)"
                            >重新分配供应商</el-button>
                            <el-popconfirm
                                title="直接终止采购订单，会同步减少要货申请单中对应物料的配送数量，请与门店沟通后再进行终止"
                                confirm-button-text="确认终止"
                                @confirm="closeOrder(scope.row, scope.$index)"
                            >
                                <template #reference>
                                    <el-button
                                        text
                                        type="primary"
                                        size="small"
                                        v-show="orgType==1&&scope.row.status!=4&&scope.row.status!=9"
                                    >终止</el-button>
                                </template>
                            </el-popconfirm>
                        </el-button-group>
                    </template>
                </el-table-column>
            </scTable>
        </el-main>
    </el-container>

    <receive-dialog
        v-if="receiveSave"
        ref="receiveDialog"
        @fatherMethod="opBindData"
        @success="handleSaveSuccess"
        @closed="receiveSave = false"
    ></receive-dialog>

    <detail-dialog
        v-if="dialogDetail"
        ref="detailDialog"
        @fatherMethod="opBindData"
        @success="handleSaveSuccess"
        @closed="dialogDetail = false"
    ></detail-dialog>

    <apply-detail-dialog
        v-if="dialogApplyDetail"
        ref="applyDetailDialog"
        @fatherMethod="opBindData"
        @success="handleSaveSuccess"
        @closed="dialogApplyDetail = false"
    ></apply-detail-dialog>
</template>

<script>
import applyDetailDialog from "../../../apply/order/detail";
import detailDialog from "./detail";
import receiveDialog from "./receive";

import publicjs from "@/api/model/publicjs";
import tool from "@/utils/tool";
import config from "@/config";

export default {
    components: {
        applyDetailDialog,
        detailDialog,
        receiveDialog,
        publicjs,
    },
    data() {
        return {
            orgType: 0,
            dialogApplyDetail: false,
            dialogDetail: false,
            receiveSave: false,
            dialogSend: false,
            dialogSendDetail: false,
            showCondition: false,
            selectionRows: [],
            pkList: ["purchaseOrderId"],
            columnList: [],
            OrderList: { purchaseOrderId: "Asc" },
            queryList: {},
            defaultQuery: {},
            result: "", // 运行结果
            props1: {
                checkStrictly: true,
                emitPath: false,
            },
            supplierProps: {
                label: "supplierName",
                value: "supplierId",
            },
            storeProps: {
                label: "storeName",
                value: "storeId",
            },
            addState: true, //可以增加
            editState: true, //可以修改
            editBatchState: true, //可以批量修改
            deleteState: true, //可以删除
            optionsState: [],
            materialTypeTree: [],
            defaultTime:[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ]
        };
    },
    methods: {
        //查看要货订单详情
        opApplyShow(row) {
            if (row.applyOrderCode) {
                this.dialogApplyDetail = true;
                this.$nextTick(() => {
                    this.$refs.applyDetailDialog.setData(row);
                    this.$refs.applyDetailDialog.open("Show");
                });
            } else {
                this.$router.push({
                    path: "/give/order",
                    query: { giveOrderCode: row.giveOrderCode },
                });
            }
        },
        //接单
        opReceive(row) {
            console.log(11);
            this.receiveSave = true;
            this.$nextTick(() => {
                this.$refs.receiveDialog.setData(row);
                this.$refs.receiveDialog.open("Add");
            });
        },
        //查看
        opShow(row) {
            if (row.orderType == 1) {
                this.$router.push({
                    path: "/delivery/order",
                    query: { deliveryOrderCode: row.deliveryOrderCode },
                });
            } else {
                this.dialogDetail = true;
                this.$nextTick(() => {
                    this.$refs.detailDialog.open("Show").setData(row);
                });
            }
        },
        //终止订单
        async closeOrder(row) {
            try {
                var returnValue = await this.$API.auth.GetProcessApi.get(
                    `refund-purchase-order/close/${row.refundPurchaseOrderId}`,
                    {}
                );
                if (returnValue.status == 200) {
                    this.$message.success("操作成功");
                    this.$refs.mytable.getData();
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        setRowClass({ row }) {
            if (this.selectionRows.includes(row)) {
                return "selected-row-color";
            }

            //终止
            if (row.status == 9) {
                return "selected-row-color-grey";
            }

            return "";
        },
        //表格选择后回调事件
        selectionChange(selection) {
            this.selectionRows = selection;
        },
        //本地更新数据
        handleSaveSuccess(data, mode) {
            if (mode == "Add") {
                this.$refs.mytable.refresh();
            } else if (mode == "Edit") {
                this.$refs.mytable.refresh();
            }
        },
        async opBindData() {
            this.$refs.mytable.clearSort();
            this.$refs.mytable.getData();
        },
        resetSearch() {
            this.queryList = {};
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/options",
                    { Codes: ["ApplyOrderStatus"] }
                );
                if (returnValue.status == 200) {
                    this.optionsState = returnValue.response.find(
                        (p) => p.code == "ApplyOrderStatus"
                    ).optionsDetails;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }

            // try {
            //     var returnValue = await this.$API.auth.PostProcessApi.post(
            //         "material-type/tree",
            //         { status: 1 }
            //     );
            //     if (returnValue.status == 200) {
            //         this.materialTypeTree = returnValue.response;
            //     } else {
            //         this.$message.error("操作失败:" + returnValue.msg);
            //     }
            // } catch (error) {
            //     this.loading = false;
            //     return false;
            // }
        },
        //供应商
        async supplierSelectProcess(rowData) {
            this.queryList.suppliers = [];
            this.queryList.supplierIds = [];
            if (rowData && rowData.length > 0) {
                rowData.map((p, index) => {
                    if (p) {
                        debugger;
                        this.queryList.suppliers = [
                            ...this.queryList.suppliers,
                            {
                                supplierId: p.supplierId,
                                supplierName: p.supplierName,
                            },
                        ];
                        this.queryList.supplierIds = [
                            ...this.queryList.supplierIds,
                            p.supplierId,
                        ];
                    }
                });
            }
            await this.opBindData();
        },
        //店铺
        async storeSelectProcess(rowData) {
            this.queryList.stores = [];
            this.queryList.storeIds = [];
            if (rowData && rowData.length > 0) {
                rowData.map((p, index) => {
                    if (p) {
                        debugger;
                        this.queryList.stores = [
                            ...this.queryList.stores,
                            {
                                storeId: p.storeId,
                                storeName: p.storeName,
                            },
                        ];
                        this.queryList.storeIds = [
                            ...this.queryList.storeIds,
                            p.storeId,
                        ];
                    }
                });
            }
            await this.opBindData();
        },
        //导出
        async exportExcel() {
            try {
                var response = await this.$API.auth.PostDownApi.post(
                    "purchase-order/export",
                    this.queryList
                );
                // 获取 Content-Disposition 头部信息
                debugger;
                const headers = new Headers(response.headers);
                console.log(headers);
                let fileName = headers.get("File-Name");
                console.log(fileName);
                fileName = decodeURIComponent(fileName);
                console.log(fileName);
                if (!fileName || fileName == "null") {
                    fileName = "采购订单.xlsx";
                }
                console.log(fileName);
                const blob = new Blob([response.data], {
                    type: "application/xlsx",
                });
                // 创建一个临时的 URL 对象，指向下载的 Blob 数据
                const url = window.URL.createObjectURL(blob);
                // 创建一个 <a> 元素，设置其 href 属性为 URL，并触发点击
                const a = document.createElement("a");
                a.href = url;
                a.download = fileName; // 下载时显示的文件名为从头信息中获取的文件名
                document.body.appendChild(a); // 将 <a> 元素添加到 DOM 中
                a.click(); // 模拟点击下载
                document.body.removeChild(a); // 下载完成后移除 <a> 元素
                window.URL.revokeObjectURL(url); // 释放 Blob 对象
            } catch (error) {
                this.loading = false;
                this.$alert(error.message, "提示", { type: "error" });
                return false;
            }
        },
        async formatDate(date) {
            if (date) {
                const dateNew = tool.formatDate(new Date(date), 1);
                console.log(dateNew);
            }
            return "";
        },
    },
    async mounted() {
        this.defaultQuery = { purchaseOrderType: [0] };
        this.queryList = { ...this.defaultQuery };
        this.orgType = tool.data.get("USER_INFO").AccountType;
        await this.initOptions();
        await this.opBindData();
    },
};
</script>
<style lang="scss" scoped>
/* 当表格行处于悬停状态时改变背景颜色 */
::v-deep .el-table .el-table__row:hover {
    background-color: #dae8f7;
}
::v-deep .el-table__body .el-table__row--striped.hover-row td {
    background-color: #dae8f7 !important;
}
//   斑马纹选中颜色
::v-deep .el-table__body .el-table__row--striped.selected-row-color td {
    background-color: #b8dcff !important;
}
::v-deep .el-table {
    --el-table-row-hover-bg-color: #dae8f7;
}
.el-table .selected-row-color-grey {
    color: #000000 !important;
    text-decoration: line-through; /* 删除线 */
}
::v-deep .el-table tr:nth-child(2n) {
    background: #f2f2f2;
}
</style>
<style>
.el-table .selected-row-color {
    background-color: #b8dcff !important;
}
.el-table--enable-row-hover .el-table__body tr.selected-row-color:hover > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper .el-table__body tr.selected-row-color.hover-row > td {
    background-color: #b8dcff !important;
}
.el-table__fixed-body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > td {
    background-color: #b8dcff !important;
}
.el-table__body-wrapper
    .el-table__body
    tr.selected-row-color.hover-row
    > .el-table__row--striped {
    background-color: #b8dcff !important;
}
</style>



